package cn.turboinfo.fuyang.api.domain.common.handler.custom;


import cn.turboinfo.fuyang.api.domain.common.service.company.HousekeepingCompanyService;
import cn.turboinfo.fuyang.api.domain.util.PhoneUtils;
import cn.turboinfo.fuyang.api.domain.util.SecurityUtils;
import cn.turboinfo.fuyang.api.domain.util.UsernameUtils;
import cn.turboinfo.fuyang.api.entity.common.pojo.company.HousekeepingCompany;
import cn.turboinfo.fuyang.api.entity.common.pojo.custom.ServiceCustom;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Component
public class ServiceCustomDataFactory {

    private final HousekeepingCompanyService housekeepingCompanyService;

    @Value("${kit.security.rsa.public-key:}")
    private String base64RSAPublicKey;

    public void assembleCompany(List<ServiceCustom> serviceCustomList) {

        Set<Long> companyIdSet = serviceCustomList.stream()
                .map(ServiceCustom::getCompanyId)
                .collect(Collectors.toSet());

        Map<Long, HousekeepingCompany> companyMap = housekeepingCompanyService.findByIdCollection(companyIdSet)
                .stream()
                .collect(Collectors.toMap(HousekeepingCompany::getId, Function.identity()));

        serviceCustomList.forEach(it -> {
            if (companyMap.containsKey(it.getCompanyId())) {
                it.setCompanyName(companyMap.get(it.getCompanyId()).getName());
            }
        });
    }

    public void maskInfo(List<ServiceCustom> serviceCustomList) {
        serviceCustomList.stream()
                .peek(this::maskInfo)
                .toList();
    }

    public ServiceCustom maskInfo(ServiceCustom serviceCustom) {
        serviceCustom.setMobileEncrypt(SecurityUtils.encodeBase64(SecurityUtils.encryptRSA(serviceCustom.getMobile().getBytes(), SecurityUtils.decodeBase64(base64RSAPublicKey))));
        serviceCustom.setMobile(PhoneUtils.maskPhoneNum(serviceCustom.getMobile()));
        serviceCustom.setContact(UsernameUtils.maskUsername(serviceCustom.getContact()));
        return serviceCustom;
    }

}
